package securityproject;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import securityproject.utils.Constants;
import securityproject.utils.RuleUtils;

public class RuleManager extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6528800911116182092L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String ruleScope = (String) req.getParameter(RuleUtils.RULE_SCOPE);

		String deleteFilesFlag = (String) (req.getParameter("deleteFiles"));
		Enumeration<?> params = req.getParameterNames();

		if ((deleteFilesFlag != null)
				&& deleteFilesFlag.equals("Delete Selected files")) {
			deleteSelectedFiles(ruleScope, params);
		} else {

			ruleSwitcher(ruleScope, params);
		}

		resp.sendRedirect("../ManageRules.jsp?" + RuleUtils.RULE_SCOPE + "="
				+ ruleScope);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doPost(req, resp);

	}

	private void ruleSwitcher(String ruleScope, Enumeration<?> params) {
		Set<String> activeRules = new HashSet<String>();

		while (params.hasMoreElements()) {

			Object elem = params.nextElement();
			if ((!(elem.toString()).equals(RuleUtils.RULE_SCOPE))
					&& (!(elem.toString().startsWith(RuleUtils.DELETE_PREFIX))))
				activeRules.add(elem.toString());

		}

		File activeXSLRulesFolder = new File(RuleUtils.getRuleFolder(ruleScope,
				true));
		File inactiveXSLRulesFolder = new File(RuleUtils.getRuleFolder(
				ruleScope, false));

		// Move all new active files from inactive folder to active folder
		for (File ruleFile : inactiveXSLRulesFolder.listFiles()) {

			if (activeRules.contains(ruleFile.getName())) {

				while (!ruleFile.renameTo(new File(activeXSLRulesFolder
						.getPath()
						+ "/" + ruleFile.getName())))
					;

			}
		}

		// Move all new inactive files from active folder to inactive folder
		for (File ruleFile : activeXSLRulesFolder.listFiles()) {

			if (!activeRules.contains(ruleFile.getName())) {
				ruleFile.renameTo(new File(inactiveXSLRulesFolder.getPath()
						+ "/" + ruleFile.getName()));
			}
		}

		deleteTmpLogs(ruleScope);
	}

	private void deleteTmpLogs(String ruleScope) {
		File tempFolder = new File(Constants.TEMP_FOLDER);

		if (ruleScope.equals("global")) {
			for (File tempFile : tempFolder.listFiles()) {
				int i = 0;
				while (!tempFile.delete() && (i < 1000)) {
					i++;
				}
			}
		} else {
			File toDeleteFile = new File(Constants.TEMP_FOLDER + ruleScope
					+ ".pdml");

			int i = 0;
			while (!toDeleteFile.delete() && (i < 1000)) {
				i++;
			}
		}
	}

	private void deleteSelectedFiles(String ruleScope, Enumeration<?> params) {
		Set<String> toDeleteRules = new HashSet<String>();

		while (params.hasMoreElements()) {

			Object elem = params.nextElement();
			if ((!(elem.toString()).equals(RuleUtils.RULE_SCOPE) && (elem
					.toString().startsWith(RuleUtils.DELETE_PREFIX))))
				toDeleteRules.add(elem.toString().substring(
						RuleUtils.DELETE_PREFIX.length()));

		}

		// Delete xml rule

		for (String rule : toDeleteRules) {

			File xmlRule = new File(RuleUtils.getXmlRule(RuleUtils
					.getRuleName(rule)));
			xmlRule.delete();
		}

		File activeXSLRulesFolder = new File(RuleUtils.getRuleFolder(ruleScope,
				true));
		File inactiveXSLRulesFolder = new File(RuleUtils.getRuleFolder(
				ruleScope, false));

		// Delete rules in inactive folder
		for (File ruleFile : inactiveXSLRulesFolder.listFiles()) {

			if (toDeleteRules.contains(ruleFile.getName())) {

				ruleFile.delete();

			}
		}

		// Delete rules in active folder
		boolean deleteActiveRules = false;
		for (File ruleFile : activeXSLRulesFolder.listFiles()) {

			if (toDeleteRules.contains(ruleFile.getName())) {
				ruleFile.delete();
				deleteActiveRules = true;

			}
		}

		if (deleteActiveRules) {
			deleteTmpLogs(ruleScope);
		}
	}

}
